package cn.edu.njust.epms.controller;

import cn.edu.njust.epms.common.R;
import cn.edu.njust.epms.common.Resp;
import cn.edu.njust.epms.entity.IORecord;
import cn.edu.njust.epms.entity.User;
import cn.edu.njust.epms.service.IOService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/io")
public class IOController {
    @Autowired
    IOService is;

    /**
     * 进出登记
     * @param record
     * @return
     */
    @PostMapping("/reg")
    public Resp<IORecord> ioReg(@RequestBody IORecord record){
        Resp<IORecord> reg = is.ioReg(record);
        return reg;
    }

    /**
     * 查询进出记录
     * @param request
     * @param r
     * @return
     */
    @PostMapping
    public Resp<PageInfo<IORecord>> selectByPage(HttpServletRequest request, @RequestBody R r){
        //从session中获取用户登录信息，对于非管理员，只能查询自己的记录，对于游客，拒绝访问
        User user = (User)request.getSession().getAttribute("user");
        if(user == null)//没有登录，拒绝访问
            return Resp.error("查询失败：拒绝访问");
        Integer uId = user.getuId();
        if(user.getuSts() != 2)
            r.setuId(uId);
        Integer _pageNo = 1;//默认分页参数
        Integer _size = 5;
        String order="rId";
        if (r.getPageNo() != null) {
            _pageNo = r.getPageNo();
        }
        if (r.getSize() != null) {
            _size = r.getSize();
        }
        if (r.getOrder()!=null && r.getOrder().length()>0) {//没有传入排序，则默认以aId排序
            order = r.getOrder();
        }
        PageHelper.startPage(_pageNo,_size,order);
        Resp<List<IORecord>> listResp = is.selectByCondition(r);
        PageInfo<IORecord> pageInfo = new PageInfo<>(listResp.getData());
        return Resp.success(pageInfo);
    }

    /**
     * 下载进出记录
     * @param request
     * @param response
     */
    @GetMapping("/download")
    public void export(HttpServletRequest request, HttpServletResponse response){
        HSSFWorkbook book = new HSSFWorkbook();
        String FileName = "IORecord_"+new SimpleDateFormat("yyyyMMddHHmmss").format(new Date())+".xls";
        HSSFSheet sheet1 = book.createSheet("sheet1");
        Resp<List<IORecord>> arrayListResp = is.selectByCondition(new R());
        List<IORecord> data = arrayListResp.getData();
        HSSFRow row0 = sheet1.createRow(0);
        sheet1.setColumnWidth(0,8*256);
        sheet1.setColumnWidth(1,17*256);
        sheet1.setColumnWidth(2,24*256);
        sheet1.setColumnWidth(3,20*256);
        sheet1.setColumnWidth(4,10*256);
        row0.createCell(0).setCellValue("进出记录ID");
        row0.createCell(1).setCellValue("进出人");
        row0.createCell(2).setCellValue("进出人身份证号");
        row0.createCell(3).setCellValue("进出时间");
        row0.createCell(4).setCellValue("状态");
        for (int i = 1; i <= data.size(); i++) {
            IORecord record = data.get(i - 1);
            HSSFRow row = sheet1.createRow(i);
            row.createCell(0).setCellValue(record.getrId());
            row.createCell(1).setCellValue(record.getUd().getName());
            row.createCell(2).setCellValue(record.getPid());
            SimpleDateFormat format = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
            row.createCell(3).setCellValue(format.format(record.getrTime()));
            row.createCell(4).setCellValue(record.isIo()?"进":"出");
        }
        response.setHeader("Content-Disposition","attachment; filename="+FileName);
        response.setContentType("application/binary;charset=ISO8859_1");
        response.setCharacterEncoding("GB2312");
        try {
            ServletOutputStream outputStream = response.getOutputStream();
            book.write(outputStream);
            outputStream.flush();
            outputStream.close();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 删除进出记录
     * 慎用！！！！
     * @param r
     * @return
     */
    @PostMapping("/delete")
    public Resp<String> deleteIORecord(IORecord r){
        return is.deleteIORecord(r);
    }
}
